package cn.itcast.xunyin.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.itcast.controller.IpBean;
import cn.itcast.xunyin.dto.XunYinGoodsList;
import cn.itcast.xunyin.dto.XunyinOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 昆仑
 */
@RestController
@Slf4j
public class XunyinController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    public  static volatile Map<String,IpBean> ret=new HashMap<>();
    @RequestMapping("/createXyMarket")
    public String createXyMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                    for(int z=0;z<tokenList.size();z++){
                        Proxy proxy=null;
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1500);
                    }

            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####草球执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品数据异常####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        String result=null;
        try{
            Long time=System.currentTimeMillis();
            Map<String,String> ret=new HashMap<>();
            ret.put("page","1");
            ret.put("pagesize","10");
            ret.put("search","");
            ret.put("time_order","");
            ret.put("price_order","1");
            ret.put("goods_id",goodsId);
            ret.put("time",time+"");
            String sign=SecureUtil.md5("1" + "1" + "10" + goodsId +""+ time);
            ret.put("sign",sign);
            result = HttpRequest.post("https://xysz.wang/api/trade/tradeGoodsListNew").formStr(ret)
                    .header("Token",token)
                    .setReadTimeout(5000)
                    .execute().body();
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(!StringUtils.isEmpty(result)){
            log.info("###########请求返回的数据############"+result);
            XunYinGoodsList
                    caoqiuGoodsList= JSONUtil.toBean(result, XunYinGoodsList.class);
            if(caoqiuGoodsList.getData()!=null && !CollectionUtils.isEmpty(caoqiuGoodsList.getData().getData())){
                log.info("###########请求返回的数据############"+result);
                List<XunYinGoodsList.XunYinGoodsDetailList> list=caoqiuGoodsList.getData().getData();
                for(XunYinGoodsList.XunYinGoodsDetailList detailDTO:list){
                    if(new BigDecimal(detailDTO.getPrice()).compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
//                        ThreadUtil.execAsync(() -> {
//                            saveOrder(finalProxy,token,detailDTO,goodsId);
//                        });
                        saveOrder(finalProxy,token,detailDTO,goodsId);
                        Thread.sleep(500);
                    }

                }
            }
        }else{
            log.info("##获取商品数据异常##");
        }
    }
    public void saveOrder(Proxy proxy, String token, XunYinGoodsList.XunYinGoodsDetailList detailDTO, String goodsId){

        String createResult=null;
        try {
            Map<String,String> ret=new HashMap<>();
            Long time=System.currentTimeMillis();
            ret.put("users_goods_id",detailDTO.getUsers_goods_id());
            ret.put("time",time+"");
            ret.put("pay_password","1b732ba5f6401a94798e514170a61d40");
            String sign=SecureUtil.md5(detailDTO.getUsers_goods_id()+time+"" +
                    "1b732ba5f6401a94798e514170a61d40");
            ret.put("sign",sign);
            createResult =
                    HttpRequest.post("https://xysz.wang/api/orders/tradeGoods").formStr(ret).header("Token",token).execute().body();
            log.info("####支付结果######"+createResult+"####"+detailDTO.getUsers_goods_id());
            XunyinOrder xunyinOrder= JSONUtil.toBean(createResult, XunyinOrder.class);
            if(xunyinOrder!=null && xunyinOrder.getCode() ==1){
                MailUtil.send("1027060531@qq.com", "草球支付", "您有一个草球的订单，请赶紧支付！", false);
            }
        } catch (Exception e) {
            log.info("####支付结果异常######"+e.getMessage()+":detailDTO"+detailDTO.toString());
        }
    }
    public void addToken(){
        tokenList.add("6100258852630685");
    }

}
